package com.jiang.jetpackdemo.adapter

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.jiang.jetpackdemo.R
import com.jiang.jetpackdemo.model.VideoRecommendInfo

/**
 *
 * @ProjectName:    JetpackDemo
 * @ClassName:      VideoAdapter
 * @Description:     java类作用描述
 * @Author:         江
 * @CreateDate:     2020/4/1 15:21
 */

class VideoAdapter(
    private val context: Context,
    private val list: MutableList<VideoRecommendInfo.ResultBean>,
    private val itemLayoutId: Int
) : RecyclerView.Adapter<VideoAdapter.ViewHolder>() {
    private val errRes = R.drawable.ic_error
    private val loadRes = R.drawable.ic_sync
    private var onClickListener: MyOnClickListener? = null

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val iv: ImageView = itemView.findViewById(R.id.iv_pic)
        val tvT: TextView = itemView.findViewById(R.id.tv_t)
        val tvC: TextView = itemView.findViewById(R.id.tv_d)
        val btn: Button? = itemView.findViewById(R.id.btn)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val v: View = LayoutInflater.from(context).inflate(itemLayoutId, parent, false)
        return ViewHolder(v)
    }

    override fun getItemCount(): Int = list.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        if (list.isNullOrEmpty()) return
        val data = list[position].data
        holder.tvC.text = data.description
        holder.tvT.text = data.title
        val feed = data?.cover?.feed
        if (feed != null) {
            Glide.with(context)
                .load(feed)
                .placeholder(loadRes)
                .error(errRes)
                .into(holder.iv)
        } else {
            holder.iv.setImageResource(errRes)
        }
        holder.btn?.setOnClickListener { onClickListener?.onClick(holder.layoutPosition) }
        holder.itemView.setOnClickListener { onClickListener?.onClick(position) }
    }

    fun setOnClickListener(onClickListener: MyOnClickListener) {
        this.onClickListener = onClickListener
    }

}